package com.molyfun.parents.service.music;

import android.text.TextUtils;

import java.util.LinkedList;
import java.util.List;

/**
 * 音乐播放观察注册类<br>
 * 状态维护 1.广播 2.注册IMusicStatus
 */

public class MusicStatusCenter {
    
    private static final String TAG = "MusicStatusCenter";

	private static String mCurrentMusicItem = "";
	
	private static MusicPlayService.State mState = MusicPlayService.State.Stopped;

	public interface IMusicStatus {
		void onMusicPlay(String musicItem);

		void onMusicPause(String musicItem);

		void onMusicStop(String musicItem);
	}

	private static List<IMusicStatus> musicStatusListeners = new LinkedList<IMusicStatus>();

    public synchronized static void registerMusicStatusListener(IMusicStatus musicStatus) {
        if (musicStatus != null && !musicStatusListeners.contains(musicStatus)) {
            musicStatusListeners.add(musicStatus);
        }
    }

    public synchronized static void unRegisterMusicStatusListener(IMusicStatus musicStatus) {
        if (musicStatus != null && musicStatusListeners.contains(musicStatus)) {
            musicStatusListeners.remove(musicStatus);
        }
    }
    
    public synchronized static void clearStatusListener() {
        musicStatusListeners.clear();
    }

	/**
	 * 通知所有观察者，播放状态的变化
	 * @param state 状态
	 * @param musicItem 音乐信息
	 */
	public static void notifyMusicStatusListener(MusicPlayService.State state,
	        String musicItem) {
	    List<IMusicStatus> list = new LinkedList<IMusicStatus>(musicStatusListeners);
	    
	    mState = state;
	    
		switch (state) {
		// Preparing和Playing统一处理，对外为play状态，若有需求区分在增加回调状态
//		case Preparing:
		case Playing:
			for (IMusicStatus musicStatus : list) {
				musicStatus.onMusicPlay(musicItem);
			}
			mCurrentMusicItem = musicItem;
			//发送状态广播
//			MediaUtils.sendPlayAction(MFPApplication.getInstance());
			break;

		case Paused:
			for (IMusicStatus musicStatus : list) {
				musicStatus.onMusicPause(musicItem);
			}
//			MediaUtils.sendPauseAction(MFPApplication.getInstance());
			break;
		case Stopped:
			for (IMusicStatus musicStatus : list) {
				musicStatus.onMusicStop(musicItem);
			}
			mCurrentMusicItem = null;
//			MediaUtils.sendStopAction(MFPApplication.getInstance());
//			 clearStatusListener();// 歌曲播放结束且回调后清空注册池
			break;
		default:
			break;
		}
	}

	/**
	 * 判断条件：音乐本地id page:mblogid + objectid、card:objectid
	 * @return 判断是否是当前播放音乐
	 */
    public static boolean isCurrentPlayingMusicItem(String musicItem) {
        if (!TextUtils.isEmpty(musicItem)) {
            if (musicItem.equals(mCurrentMusicItem)){
                return true;
            }
        }
        return false;
    }
	
    public static boolean isCurrentPlayingAudio() {
        return !TextUtils.isEmpty(mCurrentMusicItem);
    }
    
    public static String getCurrentPlayingAudio(){
        return mCurrentMusicItem;
    }
    
    public static MusicPlayService.State getCurrentPlayingAudioState(){
        return mState;
    }

}
